<template>
	<view class="container" style="padding-top:30upx">
		<span class="list">
			<view class="item-line" v-for="(item,index) in lesson_list" :key="index">
				<view class="lesson-warp">
					<view class="item"><v-competitive-summary mclass="lesson-card" :item="item" :disableNav="true"></v-competitive-summary></view>
				</view>
			</view>
			<view class="discount-total-box">
				<view class="main-box">
					<view class="discount-bar" v-if="price_discount">
						<div class="discount-label">优惠</div>
						<div class="discount-price">- {{ price_discount | price_filter }}</div>
					</view>
					<view class="discount-bar" v-if="coin_discount">
						<div class="discount-label"> <radio-box :mkey="{}" :mclass="'discount-radio'" @change="radioboxChange"></radio-box> 学情分抵扣</div>
						<div class="discount-price">- {{ coin_discount | price_filter }}</div>
					</view>
					<!-- <view class="discount-bar">
						<div class="discount-label">折上折</div>
						<div class="discount-price">-580</div>
					</view>	 -->
				</view>
			</view>
			<view class="del-all">
				<view class="total_count">
					<span class="total-price-black">合计：{{ total_price | price_filter }}</span>
					<span class="total-discount" v-if="total_discount && radioKey.enable_coin_discount">优惠：- {{ total_discount | price_filter }}</span>
				</view>
				<view class="pay-btn" @tap="orderConfirm">确认订单</view>
			</view>
		</span>
		<pay-popuper ref="popuper" :realPay="total_price"></pay-popuper>
	</view>
</template>
<script>
import competitiveSummary from './components/competitive-summary'
import rabox from './components/radio-box.vue'
import payPopuper from './components/pay-popuper'
var _this;
export default {
	props:{
		course: Object
	},
	components:{
		vCompetitiveSummary: competitiveSummary,
		radioBox: rabox,
		payPopuper
	},
	data() {
		_this = this;
		return {
			user_infos: null,
			lesson:'',
			current:'',
			subject: null,
			lesson_list: [],
			del_id_item:[],
			del_total: 0,
			price_total: 0,
			is_all: false,
			del_all:false,
			deleting: false,
			could_back: false,
			radioKey: {enable_coin_discount: false}
		};
	},
	onShow() {
		_this.user_infos = uni.getStorageSync("currentChild")
		if(!_this.user_infos){
			uni.showToast({
				title: "没有用户数据~",
				icon: 'none'
			})
		}
	},
	async onLoad(e){
		// 获取一份科目列表
		this.$zbapi.apiPost('common/subject', {}).then(res=>{
			if(res.data.code == 0){
				var sub_obj = {}
				res.data.data.forEach((item, index) => {
					sub_obj[item.subject_id] = item.subject_name
				})
				_this.subject = sub_obj
				this.loadCourse()
			}else{
				console.error("没有请求到科目列表数据")
				return uni.showToast({
					title: '网络异常',
					icon: 'none',
					complete() {
						setTimeout(uni.navigateBack, 500);
					}
				});
			}
		})
	},
	onHide() {
		uni.hideLoading()
	},
	// 返回提示
	onBackPress() {
		if(_this.could_back){
			return;
		}else if(e.from=="backbutton"){
			uni.showModal({
				title: '提示',
				content: '确定离开页面？',
				success(res) {
					if (res.confirm) { // 确定
					_this.could_back = true
						uni.navigateBack()
					} else {
						return true
					}
				}
			})
			return true
		}
	},
	onNavigationBarButtonTap(e){
		var _vm = this;
		this.deleting = !this.deleting
		// #ifdef APP-PLUS  | MP
		var webView = this.$mp.page.$getAppWebview();
		webView.setTitleNViewButtonStyle(0, {
			text: _vm.deleting ? '完成' : '编辑',
		});
		// #endif  
		this.cleanCheck()
	},
	filters:{
		totalFilter(v){
			return v.toFixed(1)
		},
		price_filter(v){
			return v && (v/100).toFixed(2)
		}
	},
	computed:{
		total_del (){
			return this.lesson_list.length && this.lesson_list.filter(x=>x.checked).length
		},
		total_price (){
			var t = [0].concat(_this.lesson_list).reduce((a,b)=>a+b.course_real_price) - _this.total_discount
			return t > 0 ? t : 0
		},
		// 优惠
		total_discount (){
			if(_this.price_discount || (_this.coin_discount && _this.radioKey.enable_coin_discount)){
				return _this.price_discount + (_this.radioKey.enable_coin_discount ? _this.coin_discount : 0)
			}
			return 0
		},
		total_coin_discount(){
			return 20
		},
		// 学情分抵扣, 后台让前端计算，需要统一算法
		coin_discount(){
			// 有学情分可以抵扣
			if(_this.user_infos.cion > 0){
				// t 为最大可抵扣, 这里按照 100 学情分 抵 1元计算
				var t = [0].concat(_this.lesson_list).reduce((a,b)=>a+b.course_real_price*b.course_discount)
				if(t<=0) return 0;
				return t >= +_this.user_infos.cion ? _this.user_infos.cion : (t - _this.user_infos.cion)
			} else {
				return 0
			}
		},
		price_discount(){
			var t = [0].concat(_this.lesson_list).reduce((a,b)=>a+(b.course_price - b.course_real_price > 0 ? b.course_price - b.course_real_price : 0))
			
			return t
		},
		couldDiscount (){
			if(this.total_price == 0) return 0
			return this.lesson_list.every(x=>+x.course_discount)
		}
	},
	methods:{
		// 加载下单课程
		loadCourse(){
			
			uni.getStorage({key: 'course', success(res){
				
				_this.$set(_this, 'lesson_list', res.data.map(item=>({
					...item,
					start_month : new Date(item.teach_start_day * 1000).format('MM.dd'),
					end_month : new Date(item.teach_end_day * 1000).format('MM.dd'),
					subject_name : _this.subject[item.subject_id],
					// 头像，最多取 4 个
					figureimgsList : item.teacher_list.map(x=>x.headimg).slice(0, 4),
					enrol_end_time : parseInt((item.enrol_end_time * 1000 - new Date()) / 86400000)    // 获取截止日期
				})))
			}})
		},
		radioboxChange (key) {
			_this.radioKey.enable_coin_discount = !_this.radioKey.enable_coin_discount
		},
		// 删除计算
		sumDel() {
			let _tv = 0
			this.selectList.forEach(x=>{_tv += (x.checked?1:0)})
			this.del_total = _tv;
		},
		// 购买计算
		sumPrice() {
			let _tv = 0, _this = this;
			this.selectList.forEach((x,i)=>{
				_tv += (x.checked ? _this.lessonList[i].productPrice*_this.lessonList[i].productNum : 0)
				})
			console.log(_tv)
			this.price_total = _tv;
		},
		// 清空选择
		cleanCheck (){
			var _vm = this;
			var _t = _vm.lesson_list.map(x=>{x.checked=!1;return x});
			_vm.$set(_vm,'lesson_list',_t);
			_vm.del_total = 0;
			_vm.price_total = 0;
			_vm.$forceUpdate();
		},
		tempdeletechange () {
			this.deleting = !this.deleting;
			this.cleanCheck()
		},
		// numbox = [newval, vm]
		numChange (numbox) {
			var idx = numbox[1].index, _t = this.lessonList[idx];
			// this.$gdapi.apiPost('/shopCar/upCar', {productNumber: _t.productNumber, productNum: numbox[0]}).then(res=>{
			// 	if(res.data.code == 200){
			// 		_t.productNum = numbox[0];
			// 		this.$set(this.lessonList, idx, _t)
			// 		this.deleting ? this.sumDel() : this.sumPrice();					
			// 	}
			// })
			// @numchange="item.productNum"
			// console.log(this.lessonList,newVal)
		},
		// 控制全选和取消全选
		changeAll: function(e) {
			var _this = this;
			// 控制全选和取消全选
			this.is_all = !this.is_all;
			var _t = this.lesson_list.map(x=>{x.checked=_this.is_all;return x})
			this.$set(this,'lesson_list',_t)
			// this.deleting ? this.sumDel() : this.sumPrice();
		},
		del(numbers, modelds){
			var _vm = this;
			if (!_vm.deleting || !_vm.del_total) return;
			var _param = numbers || _vm.selectList.filter(x=>x.checked).map(x=>x.productNumber),
				_modelds = modelds || _vm.selectList.filter(x=>x.checked).map(x=>x.modelId);
			uni.showModal({
				title: '删除商品',
				content: '确认要删除所选商品吗？',
				success: (res)=>{
					if (res.confirm) {
						// 请求删除
						this.$gdapi.apiPost('/shopCar/delCar',{
							productNumber: _param,
							modeId: _modelds
							// 还是重新加载吧，删除业务已经修改了
						}).then(function(res){
							_vm.$set(_vm, 'lessonList', _vm.lessonList.filter(x=>_modelds.indexOf(x.modelId)===-1));
							// 删除完选择置空
							_vm.cleanCheck()
						})
					}
				}
			});
		},
		togglePopup(type, open,video_id) {
			this.$refs['share'].open();
		},
		cancel(type) {
			// 关闭弹窗
			this.$refs[type].close()
		},
		// 确认订单
		orderConfirm(){
			console.log("- user infos ==> ", this.user_infos)
			var order = {
				user_id : uni.getStorageSync('currentChild').student_id,
				course_id : _this.lesson_list[0].course_id
			}
			_this.$refs.popuper.goPay(order)
		}
		,pay() {
			var _this = this;
			this.togglePopup();
			if (_this.deleting || !_this.price_total) return;
			var order_data = this.selectList.filter(x=>x.checked).map(y=>_this.lessonList.find(z=>z.modelId==y.modelId&&z.productNumber==y.productNumber))
			// 校验所选的商品的类型是否一致
			let _payMode = order_data[0].payMode;
			if (order_data.find(x=>x.payMode!==_payMode)){
				return uni.showToast({title: "不同购买类型",icon: 'none'})
			}
			this.cleanCheck();
			uni.setStorage({
				'key': "order",	// 下单
				'data': {orders: order_data, ctime: new Date().getTime()},
				success(){
					// 删除购物车商品
					// 后端沟通，处于用户体验，不在此删除 11/2
					uni.navigateTo({
						url:'../order/confirm-order',
					})
				}
			})
		}
	}
}
</script>

<style lang="scss">
page{
	background: #F7F7F7;
}
// 修改check框样式

.m-checkbox{
	width: 40upx;
	height: 40upx;
	background: #FFF;
	border: 2upx solid #ccc;
	border-radius: 50%;
	position: absolute;
	top: 100upx;
	left: 6upx;
	z-index: 101;
	font-family: iconfont;
	.uni-checkbox-input {
		color: #fff;
		width: 500rpx;
	}
	&.m-checked {
		text-align: center;
		align-items: center;
		background: #00D5A2;
		border-color: #00D5A2;
		&:after{
			content:"\e65e";
			font-weight: 800;
			color: #FFFFFF;
			/* #ifdef APP-PLUS ||MP */
			margin: 3upx 0 0 5upx;
			/* #endif */
		}
	}
}
.select-all{
	display: flex;
	align-items: center;
	color: #666;
	.all-checkbox{
		width: 40upx;
		height: 40upx;
		background: #FFF;
		border: 2upx solid #ccc;
		border-radius: 50%;
		display: inline-block;
		font-family: iconfont;
		margin: 16upx;
		.uni-checkbox-input {
			color: #fff;
			width: 500rpx;
		}
		&.m-checked {
			text-align: center;
			align-items: center;
			background: #00D5A2;
			border-color: #00D5A2;
			&:after{
				content:"\e65e";
				font-weight: 800;
				color: #FFFFFF;
				/* #ifdef APP-PLUS ||MP */
				margin: 3upx 0 0 5upx;
				/* #endif */
			}
		}
	}
}
.no-lessons{
	display: flex;
	width: 100%;
	height: 100%;
	position: relative;
	.iconkonggouwuche{
		font-size:156px ;
		color:#00D5A2 ;
		position: absolute;
		top: 40upx;
		left: 224upx;
	}
	.no-lessons-text{
		position: absolute;
		top: 476upx;
		left: 268upx;
		color: #999999;
		font-size: 26upx;
		width: 230upx;
		height: 26upx;
	}
	.no-lessons-btn{
		justify-content: center;
		align-items: center;
		background-color: #00D5A2;
		position: absolute;
		font-size: 32upx;
		color: #FFFFFF;
		top: 588upx;
		left: 232upx;
		width: 300upx;
		height: 80upx;
		line-height: 80upx;
		text-align: center;
		border-radius: 8upx;
	}
}
.icon {
	&.iconyijianfankui {
		&:before{content:"\e61b";}
	}
	// &.tianjia {
	// 	&:before{content:"\e81a";}
	// }
}

.del-all{
	width: 100%;
	height: 100upx;
	position: fixed;
	bottom: 0;
	background-color: #FFFFFF;
	border-top:4upx solid #ECECEC;
	z-index: 445 !important;
	.del-all-circle{
		position: absolute;
		left: 30upx;
		top: 30upx;
	} 
	 .del-btn{
		 width:240upx ;
		 height: 100upx;
		 background-color: #CCCCCC;
		 position: absolute;
		 right: 0;
		 color:#FFFFFF;
		 justify-content: center;
		 align-items: center;
		 &.active {
			 background: #FF7171;
		 }
	 }
	 .pay-btn{
		 display: flex;
		 width:240upx ;
		 height: 100upx;
		 background-color: #FFB800;
		 position: absolute;
		 right: 0;
		 color:#FFFFFF;
		 justify-content: center;
		 align-items: center;
	 }
	 .total_count {
		 min-width: 130upx ;
		 height: 100upx;
		 position: absolute;
		 left: 30upx;
		 color:#FFFFFF;
		 display: flex;
		 flex-direction: column;
		 .total_tip {
			 margin: 6upx 0;
			 min-width: 80upx;
			 height: 26upx;
			 font-size: 26upx;
			 font-weight:400;
			 line-height: 46upx;
			 color: #999999;
		 }
		 .total-price-black {
			 font-size: 32upx;
			 font-family:Source Han Sans CN;
			 font-weight:400;
			 color: #333;
			 margin: auto 0;
			 line-height: 1.5;
		 }
		 .total-discount {
			 font-size: 26upx;
			 font-family:Source Han Sans CN;
			 font-weight:400;
			 color: #00D5A2;
			 line-height: 1.5;
		 }
		 .total_price {
			 min-width: 68upx;
			 height: 60upx;
			 font-size: 34upx;
			 font-weight:500;
			 line-height: 60upx;
			 color: #FE2806;
			 &:before {
			 	content: "￥";
			 	font-size: inherit;
			 }
		 }
	 }
}
.list{
	flex-wrap: wrap;
	width: 100%;
	margin-top: 30upx;
	.item-line {
		min-height: 240upx;
		margin-bottom: 20upx;
		position: relative;
		.lesson-warp{
			width: 100%;
			.item {
				margin: 0 30upx;
				.lesson-card {
					background: #FFFFFF;
				}
			}
		}
	}
}
.discount-total-box {
	width: 100%;
	flex-wrap: wrap;
	.main-box {
		height: 100%;
		display: flex;
		flex-wrap: wrap;
		margin: 0 30upx;
		border-radius: 20upx;
		overflow: hidden;
	}
	.discount-bar {
		width: 100%;
		padding: 0 30upx;
		height: 80upx;
		display: inline-flex;
		justify-content: space-between;
		align-items: center;
		background: #fff;
		margin-top: 3upx;
		.discount-radio {
			margin-right: 20upx;
		}
		&:first-child {
			margin-top: 0;
		}
		.discount-label {
			font-size:26upx;
			font-family:Source Han Sans CN;
			font-weight:400;
			line-height:46upx;
			color: #999;
		}
		.discount-price {
			font-size: 26upx;
			font-family:Source Han Sans CN;
			font-weight:400;
			color: #00D5A2;
		}
	}
}
/* 底部分享 */
.uni-share {
	height: 434upx;
	background: #fff;
}
.uni-popup__mask {
	opacity: 0.3;
}
.iconweixinzhifu {color: #41B035;}
.iconzhifubao {	color: #1296DB;}
.iconjiachang {color: #00d5a2;}
.iconyinhangka {color: #2F77F1;}

.uni-share-title{line-height:60upx;color:#333;font-size:34upx;padding:15upx 0;text-align:center;border-bottom:2upx solid #e5e5e5;font-family:Source Han Sans CN;font-weight:500}
.uni-share-title>i{position:absolute;right:30upx;color:#999}
.uni-share-content{display:flex;flex-wrap:wrap;height:346upx;align-items:center}
.uni-share-content-box{display:flex;flex-direction:column;align-items:center;width:25%;box-sizing:border-box}
.uni-share-content-image{display:flex;justify-content:center;align-items:center;width:60upx;height:60upx;overflow:hidden;border-radius:10upx}
.uni-share-content-image .image{width:100%;height:100%}
.uni-share-content-image .iconfont{font-size:52upx}
.uni-share-content-text{font-size:28upx;padding-top:5px;padding-bottom:10;font-family:Source Han Sans CN;font-weight:400;color:#999}
.uni-share-btn{height:90upx;line-height:90upx;border-top:2upx #f5f5f5 solid;text-align:center;color:#666}
</style>